'use client'

import { useState, useEffect } from 'react'
import { Plus, Search, Download, Eye, Trash2, FileText, Image, Video, Archive, File, FolderOpen, Calendar, User, HardDrive, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { 
  DropdownMenu, 
  DropdownMenuContent, 
  DropdownMenuItem, 
  DropdownMenuTrigger 
} from '@/components/ui/dropdown-menu'
import { filesAPI } from '@/lib/api'
import { toast } from 'sonner'
import { FileUpload } from '@/components/files/FileUpload'
import { FileInfo, FileStats } from '@/lib/types'
import { useAuth } from '@/contexts/AuthContext'

export default function FileManagement() {
  const { user } = useAuth()
  const [files, setFiles] = useState<FileInfo[]>([])
  const [fileStats, setFileStats] = useState<FileStats | null>(null)
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedType, setSelectedType] = useState('all')
  const [isLoading, setIsLoading] = useState(true)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [showUpload, setShowUpload] = useState(false)

  const fileTypes = ['all', 'pdf', 'image', 'video', 'archive', 'document', 'other']
  
  // 检查用户权限
  const isAdmin = user?.role === 'ADMIN'
  const canDelete = isAdmin || user?.role === 'EDITOR'
  const canUpload = true // 所有用户都可以上传

  // 获取文件列表
  const fetchFiles = async () => {
    try {
      setIsLoading(true)
      // 如果不是管理员，只获取自己上传的文件
      const params = isAdmin ? {} : { userId: user?.id }
      const response = await filesAPI.getFiles(params)
      setFiles(response.files || [])
    } catch (error: any) {
      console.error('Failed to fetch files:', error)
      toast.error(error.message || '获取文件列表失败')
    } finally {
      setIsLoading(false)
    }
  }

  // 获取文件统计信息
  const fetchFileStats = async () => {
    try {
      const stats = await filesAPI.getFileStats()
      setFileStats(stats)
    } catch (error: any) {
      console.error('Failed to fetch file stats:', error)
    }
  }

  // 删除文件
  const deleteFile = async (fileId: string) => {
    if (!confirm('确定要删除这个文件吗？此操作不可撤销。')) {
      return
    }

    try {
      setIsSubmitting(true)
      await filesAPI.deleteFile(fileId)
      toast.success('文件删除成功')
      fetchFiles() // 重新获取文件列表
      fetchFileStats() // 重新获取统计信息
    } catch (error: any) {
      console.error('Failed to delete file:', error)
      toast.error(error.message || '删除文件失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 下载文件
  const downloadFile = async (file: FileInfo) => {
    try {
      if (file.url) {
        // 创建一个临时的下载链接
        const link = document.createElement('a')
        link.href = file.url
        link.download = file.originalName || file.filename
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        
        toast.success('文件下载开始')
      } else {
        toast.error('文件下载链接不可用')
      }
    } catch (error: any) {
      console.error('Failed to download file:', error)
      toast.error('文件下载失败')
    }
  }

  // 初始化加载
  useEffect(() => {
    fetchFiles()
    fetchFileStats()
  }, [])

  const filteredFiles = files.filter(file => {
    const matchesSearch = file.originalName.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         file.filename.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         file.uploadedBy.username.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesType = selectedType === 'all' || getFileTypeFromMime(file.mimeType) === selectedType
    
    return matchesSearch && matchesType
  })

  // 根据MIME类型获取文件类型
  const getFileTypeFromMime = (mimeType: string): string => {
    if (mimeType.startsWith('image/')) return 'image'
    if (mimeType.startsWith('video/')) return 'video'
    if (mimeType.startsWith('audio/')) return 'audio'
    if (mimeType === 'application/pdf') return 'pdf'
    if (mimeType.includes('zip') || mimeType.includes('rar') || mimeType.includes('7z')) return 'archive'
    if (mimeType.includes('document') || mimeType.includes('word') || mimeType.includes('excel') || mimeType.includes('powerpoint')) return 'document'
    return 'other'
  }

  // 修复文件名编码问题
  const getDisplayFileName = (file: FileInfo): string => {
    try {
      // 优先使用 originalName，如果为空则使用 filename
      const fileName = file.originalName || file.filename || '未知文件'
      
      // 检测是否为编码后的文件名（包含 % 字符）
      if (fileName.includes('%')) {
        try {
          // 直接 URL 解码
          const decodedName = decodeURIComponent(fileName)
          console.log('解码文件名:', fileName, '->', decodedName)
          return decodedName
        } catch (error) {
          console.error('文件名解码失败:', error)
          return fileName
        }
      }
      
      // 检测是否为中文乱码（包含 å 字符）- 兼容旧数据
      if (fileName.includes('å') || fileName.includes('ç') || fileName.includes('ä') || fileName.includes('è')) {
        console.log('检测到可能的编码问题:', fileName)
        
        // 尝试修复常见的编码问题
        const commonFixes: { [key: string]: string } = {
          'åå¸': '公司',
          'ç»ä»': '组织',
          'åºå°': '架构',
          'è£': '安装'
        }
        
        let fixedName = fileName
        Object.entries(commonFixes).forEach(([wrong, correct]) => {
          fixedName = fixedName.replace(new RegExp(wrong, 'g'), correct)
        })
        
        if (fixedName !== fileName) {
          console.log('常见编码修复成功:', fixedName)
          return fixedName
        }
        
        // 如果修复失败，尝试从文件扩展名推断
        if (fileName.endsWith('.pdf')) {
          return `文档_${file.id}.pdf`
        } else if (fileName.endsWith('.jpg') || fileName.endsWith('.png')) {
          return `图片_${file.id}.${fileName.split('.').pop()}`
        } else {
          return `文件_${file.id}.${fileName.split('.').pop() || 'unknown'}`
        }
      }
      
      return fileName
    } catch (error) {
      console.error('Error processing filename:', error)
      return file.originalName || file.filename || '未知文件'
    }
  }

  // 智能判断文件状态
  const getFileStatus = (file: FileInfo): { status: string; variant: 'default' | 'secondary' | 'destructive'; className?: string } => {
    // 检查文件是否完整
    const hasPath = file.path && file.path.trim() !== ''
    const hasUrl = file.url && file.url.trim() !== ''
    const hasValidSize = file.size > 0
    const hasValidMimeType = file.mimeType && file.mimeType.trim() !== ''
    
    // 如果所有必要字段都存在且有效，文件状态正常
    if (hasPath && hasUrl && hasValidSize && hasValidMimeType) {
      return {
        status: '正常',
        variant: 'default',
        className: 'bg-green-100 text-green-800'
      }
    }
    
    // 如果缺少关键字段，文件状态异常
    if (!hasPath || !hasUrl) {
      return {
        status: '路径缺失',
        variant: 'destructive',
        className: 'bg-red-100 text-red-800'
      }
    }
    
    if (!hasValidSize) {
      return {
        status: '大小异常',
        variant: 'secondary'
      }
    }
    
    if (!hasValidMimeType) {
      return {
        status: '类型异常',
        variant: 'secondary'
      }
    }
    
    // 其他情况
    return {
      status: '未知',
      variant: 'secondary'
    }
  }

  const totalFiles = files.length
  const totalSize = files.reduce((sum, f) => sum + f.size, 0)
  const activeFiles = files.filter(f => {
    const status = getFileStatus(f)
    return status.status === '正常'
  })

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  const getFileIcon = (mimeType: string) => {
    const type = getFileTypeFromMime(mimeType)
    switch (type) {
      case 'pdf':
        return <FileText className="h-8 w-8 text-red-500" />
      case 'image':
        return <Image className="h-8 w-8 text-green-500" />
      case 'video':
        return <Video className="h-8 w-8 text-purple-500" />
      case 'audio':
        return <File className="h-8 w-8 text-blue-500" />
      case 'archive':
        return <Archive className="h-8 w-8 text-orange-500" />
      case 'document':
        return <FileText className="h-8 w-8 text-blue-600" />
      default:
        return <File className="h-8 w-8 text-gray-500" />
    }
  }

  const getFileTypeBadge = (mimeType: string) => {
    const type = getFileTypeFromMime(mimeType)
    const typeNames: { [key: string]: string } = {
      'pdf': 'PDF',
      'image': '图片',
      'video': '视频',
      'audio': '音频',
      'archive': '压缩包',
      'document': '文档',
      'other': '其他'
    }
    return <Badge variant="outline">{typeNames[type] || '其他'}</Badge>
  }

  const getStatusBadge = (file: FileInfo) => {
    const fileStatus = getFileStatus(file)
    return (
      <Badge variant={fileStatus.variant} className={fileStatus.className}>
        {fileStatus.status}
      </Badge>
    )
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="flex items-center space-x-2">
          <Loader2 className="h-6 w-6 animate-spin" />
          <span>加载文件数据中...</span>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">文件管理</h1>
          <p className="text-gray-600 mt-1">管理系统上传的文件和资源</p>
        </div>
        <Button onClick={() => setShowUpload(true)}>
          <Plus className="h-4 w-4 mr-2" />
          上传文件
        </Button>
      </div>

      {/* 文件统计 */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center space-x-2">
              <File className="h-5 w-5 text-blue-600" />
              <div>
                <p className="text-sm text-muted-foreground">
                  {isAdmin ? '总文件数' : '我的文件数'}
                </p>
                <p className="text-2xl font-bold">{fileStats?.totalFiles || totalFiles}</p>
                {!isAdmin && (
                  <p className="text-xs text-muted-foreground">仅显示您上传的文件</p>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center space-x-2">
              <HardDrive className="h-5 w-5 text-green-600" />
              <div>
                <p className="text-sm text-muted-foreground">
                  {isAdmin ? '总存储空间' : '我的存储空间'}
                </p>
                <p className="text-2xl font-bold">{formatFileSize(fileStats?.totalSize || totalSize)}</p>
                {!isAdmin && (
                  <p className="text-xs text-muted-foreground">仅统计您的文件</p>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center space-x-2">
              <Download className="h-5 w-5 text-purple-600" />
              <div>
                <p className="text-sm text-muted-foreground">文件类型</p>
                <p className="text-2xl font-bold">{fileStats?.filesByType?.length || 0}</p>
                {!isAdmin && (
                  <p className="text-xs text-muted-foreground">您的文件类型分布</p>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center space-x-2">
              <FolderOpen className="h-5 w-5 text-orange-600" />
              <div>
                <p className="text-sm text-muted-foreground">正常文件</p>
                <p className="text-2xl font-bold">{activeFiles.length}</p>
                {!isAdmin && (
                  <p className="text-xs text-muted-foreground">您的有效文件</p>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
      
      {/* 权限提示 */}
      {!isAdmin && (
        <Card className="bg-blue-50 border-blue-200">
          <CardContent className="p-4">
            <div className="flex items-center space-x-2">
              <div className="h-2 w-2 bg-blue-500 rounded-full"></div>
              <p className="text-sm text-blue-700">
                您当前以 <strong>{user?.role}</strong> 身份登录，只能查看和管理自己上传的文件。
                {user?.role === 'EDITOR' && ' 您可以删除自己上传的文件。'}
                {user?.role === 'VIEWER' && ' 您只能查看文件，无法删除。'}
              </p>
            </div>
          </CardContent>
        </Card>
      )}

      {/* 搜索和筛选 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">搜索和筛选</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex flex-col sm:flex-row gap-4">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="搜索文件名或上传者..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-8"
                />
              </div>
            </div>
            <div className="flex gap-2">
              <select
                value={selectedType}
                onChange={(e) => setSelectedType(e.target.value)}
                className="px-3 py-2 border border-input rounded-md bg-background text-sm"
              >
                {fileTypes.map(type => (
                  <option key={type} value={type}>
                    {type === 'all' ? '全部类型' : 
                     type === 'pdf' ? 'PDF' :
                     type === 'image' ? '图片' :
                     type === 'video' ? '视频' :
                     type === 'audio' ? '音频' :
                     type === 'archive' ? '压缩包' :
                     type === 'document' ? '文档' : '其他'}
                  </option>
                ))}
              </select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 文件列表 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">文件列表 ({filteredFiles.length})</CardTitle>
        </CardHeader>
        <CardContent>
          {filteredFiles.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">
              暂无文件数据
            </div>
          ) : (
            <div className="space-y-4">
              {filteredFiles.map((file) => (
                <div
                  key={file.id}
                  className="flex items-center justify-between p-4 border border-border rounded-lg hover:bg-accent/50 transition-colors"
                >
                  <div className="flex items-center space-x-4">
                    {getFileIcon(file.mimeType)}
                    <div>
                      <div className="flex items-center space-x-3">
                        <h3 className="text-lg font-medium">{getDisplayFileName(file)}</h3>
                        {getFileTypeBadge(file.mimeType)}
                        {getStatusBadge(file)}
                      </div>
                      {/* 编码修复提示 */}
                      {(file.originalName || file.filename) && 
                       ((file.originalName || file.filename).includes('å') || 
                        (file.originalName || file.filename).includes('%')) && 
                       getDisplayFileName(file) !== (file.originalName || file.filename) && (
                        <div className="text-xs text-amber-600 bg-amber-50 px-2 py-1 rounded mt-1 inline-block">
                          🔧 文件名已自动修复编码问题
                        </div>
                      )}
                      <div className="flex items-center space-x-4 mt-2 text-sm text-muted-foreground">
                        <span className="flex items-center space-x-1">
                          <User className="h-4 w-4" />
                          <span>{file.uploadedBy.username}</span>
                        </span>
                        <span className="flex items-center space-x-1">
                          <Calendar className="h-4 w-4" />
                          <span>{new Date(file.createdAt).toLocaleString()}</span>
                        </span>
                        <span>大小: {formatFileSize(file.size)}</span>
                        <span>类型: {file.mimeType}</span>
                      </div>
                      {/* 调试信息 - 开发环境显示 */}
                      {process.env.NODE_ENV === 'development' && (
                        <div className="mt-2 text-xs text-gray-400 space-y-1">
                          <div>ID: {file.id}</div>
                          <div>Path: {file.path || 'null'}</div>
                          <div>URL: {file.url || 'null'}</div>
                          <div>Filename: {file.filename || 'null'}</div>
                          <div>OriginalName: {file.originalName || 'null'}</div>
                        </div>
                      )}
                    </div>
                  </div>
                  
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="icon">
                        <File className="h-4 w-4" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      <DropdownMenuItem>
                        <Eye className="h-4 w-4 mr-2" />
                        预览
                      </DropdownMenuItem>
                      <DropdownMenuItem 
                        onClick={() => downloadFile(file)}
                        disabled={isSubmitting}
                      >
                        <Download className="h-4 w-4 mr-2" />
                        下载
                      </DropdownMenuItem>
                      {/* 只有管理员或文件所有者可以删除文件 */}
                      {(isAdmin || (canDelete && file.uploadedBy.id === user?.id)) && (
                        <DropdownMenuItem 
                          className="text-destructive"
                          onClick={() => deleteFile(file.id)}
                          disabled={isSubmitting}
                        >
                          <Trash2 className="h-4 w-4 mr-2" />
                          删除
                        </DropdownMenuItem>
                      )}
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* 存储空间使用情况 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">存储空间使用情况</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <span className="text-sm font-medium">已使用空间</span>
              <span className="text-sm text-muted-foreground">
                {formatFileSize(fileStats?.totalSize || totalSize)} / 10 GB
              </span>
            </div>
            <div className="w-full bg-gray-200 rounded-full h-2">
              <div 
                className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                style={{ width: `${Math.min(((fileStats?.totalSize || totalSize) / (10 * 1024 * 1024 * 1024)) * 100, 100)}%` }}
              />
            </div>
            {fileStats?.filesByType && (
              <div className="grid gap-4 md:grid-cols-3 text-sm">
                {fileStats.filesByType.slice(0, 3).map((typeInfo, index) => {
                  // 验证数据完整性
                  if (!typeInfo || typeof typeInfo.totalSize !== 'number' || isNaN(typeInfo.totalSize)) {
                    return null
                  }
                  
                  const fileType = getFileTypeFromMime(typeInfo.mimeType)
                  const typeDisplayName = fileType === 'image' ? '图片文件' : 
                                        fileType === 'video' ? '视频文件' : 
                                        fileType === 'pdf' ? 'PDF文件' : 
                                        fileType === 'audio' ? '音频文件' :
                                        fileType === 'archive' ? '压缩文件' :
                                        fileType === 'document' ? '文档文件' : '其他文件'
                  
                  return (
                    <div key={index} className="flex items-center justify-between">
                      <span>{typeDisplayName}</span>
                      <span className="text-muted-foreground">
                        {formatFileSize(typeInfo.totalSize)}
                      </span>
                    </div>
                  )
                }).filter(Boolean)}
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* 文件上传弹窗 */}
      {showUpload && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="w-full max-w-4xl">
            <FileUpload
              onClose={() => {
                setShowUpload(false)
                // 🔴 确保关闭弹窗时也刷新数据
                fetchFiles() // 重新获取文件列表
                fetchFileStats() // 重新获取统计信息
              }}
              onUploadSuccess={() => {
                setShowUpload(false)
                fetchFiles() // 重新获取文件列表
                fetchFileStats() // 重新获取统计信息
              }}
            />
          </div>
        </div>
      )}
    </div>
  )
}
